package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"log"
	"math/rand"
	"net/http"
	"time"
)

type User struct {
	gorm.Model
	Username string		`gorm:"type:varchar(20);not null;unique_index"`
	Password string		`gorm:"type:varchar(18);not null"`
	Telephone string	`gorm:"type:varchar(11);not null"`
}

func main() {
	db := InitDB()
	defer db.Close()
	r := gin.Default()
	r.POST("/api/auth/register", func(c *gin.Context) {

		// 获取参数
		username := c.PostForm("username")
		password := c.PostForm("password")
		telephone := c.PostForm("telephone")
		// 校验参数
		if len(telephone) != 11 {
			c.JSON(http.StatusUnprocessableEntity, gin.H{
				"code":    422,
				"message": "手机号必须为11位",
			})
			return
		}

		if len(password) < 6{
			c.JSON(http.StatusUnprocessableEntity, gin.H{
				"code": 422,
				"message": "密码不能少于6位",
			})
			return
		}


		if len(username) == 0 {
			username = RandomString(10)
		}
		log.Println(username, password, telephone)
		// 判断手机号是否存在
		if isTelephoneExist(db, telephone) {
			c.JSON(http.StatusUnprocessableEntity, gin.H{
				"code":    422,
				"message": "手机号已存在",
			})
			return
		}
		// 创建用户
		newUser := User{
			Username: username,
			Password: password,
			Telephone: telephone,
		}
		db.Create(&newUser)

		c.JSON(http.StatusOK, gin.H{
			"message": "注册成功",
		})
	})
	panic(r.Run())
}

func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user User
	db.Where("telephone = ?", telephone).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}

func RandomString(i int) string {
	var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	result := make([]byte, i)

	rand.Seed(time.Now().Unix())
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

func InitDB() *gorm.DB{
	driverName := "mysql"
	host := "localhost"
	port := "3306"
	database := "hbt_sys"
	username := "root"
	password := "root"
	charset := "utf8"
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)
	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic("连接数据库失败")
	}
	return db
}
